/**
 * 
 */
package com.couchcrowler.shared;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author vienozin
 *
 */
public class RetryMap<K> {

	private int maxRetries;
	
	private final Map<K, Integer> retries = new TreeMap<K, Integer>();
	
	public RetryMap(int maxRetries) {
		this.maxRetries = maxRetries;
	}
	
	private int getRetryCount(K element) {
		Integer retries = this.retries.get(element);
		if (retries == null) {
			retries = 0;			
		} else {
			retries++;
		}
		
		this.retries.put(element, retries);
		
		return retries;
	}

	public Collection<K> retry(Collection<K> elements) {
		Collection<K> result = new ArrayList<K>();
		for (K element : elements) {
			if (getRetryCount(element) < maxRetries) {
				result.add(element);
			}
		}		
		
		return result;
	}
}
